package inventoryRecord

import (
	"context"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/shopspring/decimal"
	"insighttracking/apps/admin/auth"
	"insighttracking/query/bo"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetInventoryRecordPageApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetInventoryRecordPageApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetInventoryRecordPageApiLogic {
	hostname, _ := os.Hostname()
	return &GetInventoryRecordPageApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetInventoryRecordPageApiLogic) GetInventoryRecordPageApi(req *types.GetInventoryRecordPageReq) (resp *types.GetInventoryRecordPageResp, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return nil, err
	}
	spuBo, count, err := service.SpuService.GetSpuPageApi(l.ctx, bo.SpuPageBoReq{
		Name:         req.Name,                 // 商品名称
		PageSize:     req.PageSize,             // 当前条数
		PageNumber:   req.PageNumber,           // 当前页数
		EnterpriseID: accountInfo.EnterpriseId, // 关联到enterprise表主键id
	})
	if err != nil {
		return &types.GetInventoryRecordPageResp{
			Data: make([]types.InventoryRecordResp, 0),
			PageBaseResp: types.PageBaseResp{
				Total:      0,
				PageNumber: req.PageNumber,
				PageSize:   req.PageSize,
			},
		}, nil
	}
	spuIdList := k.Map(spuBo, func(item bo.SpuBo, index int) int64 {
		return item.ID
	})
	// 查询库存
	spuInventoryMap := service.SpuInventoryService.SpuInventoryBySpuIdListAPi(l.ctx, spuIdList, 0)
	var result = make([]types.InventoryRecordResp, 0)
	for _, item := range spuBo {
		inventory, isOk := spuInventoryMap[item.ID]
		result = append(result, types.InventoryRecordResp{
			ID:             item.ID,                                            // 主键id
			Name:           item.Name,                                          // 商品名称
			CategoryName:   item.CategoryName,                                  // 单位分类名称
			UnitName:       item.UnitName,                                      // 单位名称
			InventoryCount: k.If(isOk, inventory, decimal.Zero).StringFixed(2), // 库存数量
		})
	}
	return &types.GetInventoryRecordPageResp{
		Data: result,
		PageBaseResp: types.PageBaseResp{
			Total:      count,
			PageNumber: req.PageNumber,
			PageSize:   req.PageSize,
		},
	}, nil
}
